﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using com.lover.astd.common.model;

namespace com.lover.astd.common.config
{
    public class GameConfig
    {
        private const string ConfFileName = "astool.ini";
        private string _dirname = "";
        private string _filename = "";
        private bool _inited = false;
        /// <summary>
        /// 是否已经初始化完毕, 也就是说是否已经保存过
        /// </summary>
        public bool Inited { get { return _inited; } }
        private Dictionary<string, Dictionary<string, string>> _configAll = new Dictionary<string,Dictionary<string,string>>();
        public Dictionary<string, Dictionary<string, string>> getAllConfig() { return _configAll; }
        public Dictionary<string, string> getConfig(string configName)
        {
            if (_configAll.ContainsKey(configName)) return _configAll[configName];
            else
            {
                Dictionary<string, string> conf = new Dictionary<string, string>();
                _configAll.Add(configName, conf);
                return conf;
            }
        }
        public void setConfig(string configName, Dictionary<string, string> conf)
        {
            foreach (string key in conf.Keys)
            {
                setConfig(configName, key, conf[key]);
            }
        }
        public void setConfig(string mainConfigName, string subConfigName, string conf)
        {
            if (_configAll.ContainsKey(mainConfigName))
            {
                Dictionary<string, string> sub = _configAll[mainConfigName];
                if (sub.ContainsKey(subConfigName)) sub[subConfigName] = conf;
                else sub.Add(subConfigName, conf);
            }
            else
            {
                Dictionary<string, string> sub = new Dictionary<string, string>();
                sub.Add(subConfigName, conf);
                _configAll.Add(mainConfigName, sub);
            }
        }
        public GameConfig(string partner, int serverid, string rolename)
        {
            string top_dir = "accounts";
            string pure_dir = String.Format("{0}_{1}_{2}", partner, serverid, rolename);
            _dirname = String.Format("{0}/{1}", top_dir, pure_dir);
            _filename = String.Format("{0}/{1}", _dirname, ConfFileName);
            DirectoryInfo dirinfo = new DirectoryInfo(_dirname);
            if (!dirinfo.Exists)
            {
                // 判断是否有以前的文件夹存在, 如果有, 则改名
                string dirname_too_old = rolename;
                string dirname_former = String.Format("{0}/{1}", top_dir, rolename);
                if (Directory.Exists(dirname_too_old))
                {
                    if (!Directory.Exists(top_dir)) Directory.CreateDirectory(top_dir);
                    Directory.Move(dirname_too_old, _dirname);
                }
                if (Directory.Exists(dirname_former)) Directory.Move(dirname_former, _dirname);
                if (!Directory.Exists(_dirname)) dirinfo.Create();
            }
        }
        public bool loadSettings()
        {
            FileInfo finfo = new FileInfo(_filename);
            if (!finfo.Exists)
            {
                return false;
            }
            _inited = true;
            StreamReader fr = finfo.OpenText();
            string[] spliters = new string[] { "=" };
            string key = null, value = null;
            string[] substrs = null;
            string line = fr.ReadLine();
            while (line != null)
            {
                line = line.Trim();
                if (line.Length > 0 && !line.StartsWith("#"))
                {
                    substrs = line.Split(spliters, StringSplitOptions.RemoveEmptyEntries);
                    if (substrs.Length == 2)
                    {
                        key = substrs[0]; value = substrs[1];
                        if (key != null && value != null && key.Length > 0 && value.Length > 0)
                        {
                            handleConfigPair(key, value);
                        }
                    }
                }
                line = fr.ReadLine();
            }
            fr.Close();
            return true;
        }
        private void handleConfigPair(string key, string value)
        {
            string[] subkeys = key.Split(new string[]{"."}, StringSplitOptions.RemoveEmptyEntries);
            if (subkeys.Length < 2) return;
            string main = subkeys[0].Trim();
            string sub = subkeys[1].Trim();
            setConfig(main, sub, value);
        }
        public void saveSettings()
        {
            FileInfo finfo = new FileInfo(_filename);
            FileStream stream = null;
            if (!finfo.Exists)
            {
                stream = finfo.Create();
            }
            else stream = finfo.Open(FileMode.Truncate, FileAccess.Write);
            _inited = true;
            StreamWriter wr = new StreamWriter(stream);
            wr.WriteLine("# astd tools ini file, please donnot change this file by yourself");

            foreach (string main in _configAll.Keys)
            {
                wr.WriteLine("# " + main);
                Dictionary<string, string> subconfs = _configAll[main];
                foreach (string sub in subconfs.Keys)
                {
                    string str = String.Format("{0:s}.{1:s}={2:s}", main, sub, subconfs[sub]);
                    wr.WriteLine(str);
                }
                wr.WriteLine();
            }

            wr.Close();
            stream.Close();
        }
    }
}
